package com.xlz.timer;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xlz.domain.AppInstance;
import com.xlz.manager.DefaultDstManager;
import com.xlz.service.AppInstanceService;
import com.xlz.service.AppWorkerService;

/**
 * 清空过期task
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class CleanTask implements Runnable {

	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	private DefaultDstManager scheduleManager;
	private AppInstanceService appInstanceService;
	private AppWorkerService appWorkerService;

	public CleanTask(DefaultDstManager scheduleManager) {
		this.scheduleManager = scheduleManager;
		appInstanceService = scheduleManager.getAppInstanceService();
		appWorkerService = scheduleManager.getAppWorkerService();
	}

	@Override
	public void run() {
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		try {
			//if (scheduleManager.getContext().isMaster()) {
				long start = System.currentTimeMillis();
				// 修改状态为不可用
				List<AppInstance> instances = appInstanceService.getDeadAllByAppNo(scheduleManager.getContext().getAppNo(),
						scheduleManager.getContext().getDeadHeartCount()
						* scheduleManager.getContext().getHeartBeatRate());
				
				for(AppInstance entity : instances){
					//删除worker
					appWorkerService.deleteByRegisterInstanceId(entity.getRegisterInstanceId());
					appInstanceService.deleteByAppId(entity.getId());
				}
				long end = System.currentTimeMillis();
				LOG.debug("清空过去实例和工作组成功，耗时{}ms",(end-start));
			//}
		} catch (Exception e) {
			LOG.error("清空已经超时的数据：{}", scheduleManager.getContext().getInstanceId(), e);
		}
	}

}
